package com.easylinkin.linkappapi.progress.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.progress.entity.ProgressWarnConfig;
import com.easylinkin.linkappapi.progress.mapper.ProgressWarnConfigMapper;
import com.easylinkin.linkappapi.progress.service.ProgressWarnConfigService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.List;

/**
 * ProgressWarnConfig表服务实现类
 *
 * @author zhengwen
 * @date 2023/11/22
 */
@Slf4j
@Service("appProgressWarnConfigService")
public class ProgressWarnConfigServiceImpl extends ServiceImpl
        <ProgressWarnConfigMapper, ProgressWarnConfig> implements ProgressWarnConfigService {
    @Resource
    private CommonService commonService;

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Override
    public boolean removeById(Serializable id) {
        return super.update().set("deleted_", id).eq("id_", id).update();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<Long> idList) {
        // 将删除状态改为主键值
        new LambdaUpdateChainWrapper<>(getBaseMapper()).setSql("deleted_ = id_").in(ProgressWarnConfig::getId, idList).update();
        return true;
    }


    @Override
    public boolean saveOne(ProgressWarnConfig appProgressWarnConfig) {
        commonService.setCreateAndModifyInfo(appProgressWarnConfig);

        validParamRequired(appProgressWarnConfig);
        validRepeat(appProgressWarnConfig);
        validParamFormat(appProgressWarnConfig);
        return save(appProgressWarnConfig);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOne(ProgressWarnConfig appProgressWarnConfig) {
        Assert.notNull(appProgressWarnConfig.getId(), "id不能为空");
        commonService.setModifyInfo(appProgressWarnConfig);

        validRepeat(appProgressWarnConfig);
        validParamFormat(appProgressWarnConfig);
        return updateById(appProgressWarnConfig);
    }

    @Override
    public IPage<ProgressWarnConfig> selectPage(Page page, ProgressWarnConfig appProgressWarnConfig) {
        return baseMapper.selectPage(page, appProgressWarnConfig);
    }

    @Override
    public void export(ProgressWarnConfig appProgressWarnConfig, HttpServletRequest request, HttpServletResponse
            response) {

    }

    @Override
    public RestMessage getProgressWarnConfig() {
        //获取当前用户
        LinkappUser linkappUser = linkappUserContextProducer.getCurrent();
        Assert.notNull(linkappUser, "租户信息为空");
        //获取当前用户的租户id
        String tenantId = linkappUser.getTenantId();
        Assert.isTrue(StringUtils.isNotBlank(tenantId), "租户id为空");

        //获取当前用户的租户下的最新配置信息
        QueryWrapper<ProgressWarnConfig> qw = new QueryWrapper<>();
        qw.eq("tenant_id_", tenantId);
        qw.orderByDesc("create_time_");
        qw.last("limit 1");
        ProgressWarnConfig progressWarnConfig = getOne(qw);
        //Assert.notNull(progressWarnConfig, "进度预警配置为空");

        return RestBuilders.successBuilder().data(progressWarnConfig).build();
    }

    @Override
    public RestMessage saveOrUpdateProgressWarnConfig(ProgressWarnConfig progressWarnConfig) {
        //获取当前用户
        LinkappUser linkappUser = linkappUserContextProducer.getCurrent();
        Assert.notNull(linkappUser, "用户登录信息为空");

        //获取当前用户的租户id
        String tenantId = linkappUser.getTenantId();
        Assert.isTrue(StringUtils.isNotBlank(tenantId), "租户id为空");

        //获取当前用户的租户下的最新配置信息
        QueryWrapper<ProgressWarnConfig> qw = new QueryWrapper<>();
        qw.eq("tenant_id_", tenantId);
        qw.orderByDesc("create_time_");
        qw.last("limit 1");
        ProgressWarnConfig oldConfig = getOne(qw);

        //校验参数
        validParamRequired(progressWarnConfig);
        //设置租户id
        progressWarnConfig.setTenantId(tenantId);

        //如果没有配置信息，则新增
        if (oldConfig == null) {

            commonService.setCreateAndModifyInfo(progressWarnConfig);
            saveOne(progressWarnConfig);
        } else {
            //如果有配置信息，则更新（更新需要比较数据变化，如果没有变化就不更新，避免触发重新计算）
            boolean isSame = compConfigSame(oldConfig, progressWarnConfig);
            if (!isSame) {
                //如果不相同，则更新
                commonService.setModifyInfo(progressWarnConfig);
                progressWarnConfig.setId(oldConfig.getId());
                updateOne(progressWarnConfig);
            }
        }

        return RestBuilders.successBuilder().build();
    }

    /**
     * 比较两个配置是否相同
     *
     * @param oldConfig          旧配置
     * @param progressWarnConfig 新配置
     * @return 是否相同
     */
    private boolean compConfigSame(ProgressWarnConfig oldConfig, ProgressWarnConfig progressWarnConfig) {
        if (oldConfig.getFinishLess().equals(progressWarnConfig.getFinishLess())
                && oldConfig.getFinishMore().equals(progressWarnConfig.getFinishMore())
                && oldConfig.getUndoneLess().equals(progressWarnConfig.getUndoneLess())
                && oldConfig.getUndoneMore().equals(progressWarnConfig.getUndoneMore())
                && oldConfig.getParentFinishLess().equals(progressWarnConfig.getParentFinishLess())
                && oldConfig.getParentFinishMore().equals(progressWarnConfig.getParentFinishMore())
                && oldConfig.getParentUndoneLess().equals(progressWarnConfig.getParentUndoneLess())
                && oldConfig.getParentUndoneMore().equals(progressWarnConfig.getParentUndoneMore())) {
            return true;
        }
        return false;
    }

    @Override
    public ProgressWarnConfig getOneById(Serializable id) {
        return baseMapper.getOneById(id);
    }

    /**
     * 校验重复
     */
    private void validRepeat(ProgressWarnConfig appProgressWarnConfig) {

        /* List<ProgressWarnConfig> list = new LambdaQueryChainWrapper<>(baseMapper)
            .eq(ProgressWarnConfig::getDeviceCode, appProgressWarnConfig.getDeviceCode())
            .list();
            if (list.size() > 0 && (list.size() > 1 || ObjectUtils.isEmpty(appProgressWarnConfig.getId()) || !appProgressWarnConfig.getId().equals(list.get(0).getId()))) {
                throw new BusinessException("名称重复");
            }
        */


    }


    /**
     * 校验参数必填
     */
    private void validParamRequired(ProgressWarnConfig progressWarnConfig) {
        Assert.notNull(progressWarnConfig, "参数为空");
        Assert.notNull(progressWarnConfig.getFinishLess(), "实际完成百分比为100%时，预警下限不能为空");
        Assert.notNull(progressWarnConfig.getFinishMore(), "实际完成百分比为100%时，预警上限不能为空");
        Assert.notNull(progressWarnConfig.getUndoneLess(), "实际未完成百分比为100%时，预警下限不能为空");
        Assert.notNull(progressWarnConfig.getUndoneMore(), "实际未完成百分比为100%时，预警上限不能为空");

        Assert.notNull(progressWarnConfig.getParentFinishLess(), "父级实际完成百分比为100%时，预警下限不能为空");
        Assert.notNull(progressWarnConfig.getParentFinishMore(), "父级实际完成百分比为100%时，预警上限不能为空");
        Assert.notNull(progressWarnConfig.getParentUndoneLess(), "父级实际未完成百分比为100%时，预警下限不能为空");
        Assert.notNull(progressWarnConfig.getParentUndoneMore(), "父级实际未完成百分比为100%时，预警上限不能为空");
    }

    /**
     * 校验参数格式
     */
    private void validParamFormat(ProgressWarnConfig appProgressWarnConfig) {
        //Assert.isTrue(appProgressWarnConfig.getName() == null || appProgressWarnConfig.getName().length() <= 50,
        //        "名称超长");
    }
}

